<?php
namespace app\file\controller;
use think\Request;
use app\file\controller\File;
use PHPExcel_IOFactory;
use think\Exception;
class ExportExcel extends File
{
    private $excelData = [];//导入数据
    protected $model = null;//导入数据调用模型
    protected $ty = null;//导入模型
    protected $type = null;//导入模型分类
    protected $head = [];//下载模版头部
    protected $name = '';//下载模版名字

    /**
	 * 导入模版
	 */
	public function export_excel()
	{
		if(Request()->isGet()){
			return $this->fetch('export');
		}
		if(Request()->isAjax()){
			
            $this->validateFile();
            $this->getFileData();
            $this->exportModel();
            try{
                $this->model->startTrans();
                $res = $this->model->exportData($this->excelData, $this->ty, $this->type);
                if($res === false){
                    $this->model->rollback();
                    $this->error($this->model->getError());
                }
                $this->model->commit();
                $this->success(config('status.SUCCESS_ONE'));
            }catch(Exception $e){
                $this->model->rollback();
                $this->error(config('status.ERROR_FIVE').$e->getMessage());
            }
		}
    }
    /**
    * 下载模版
    */
    public function download_csv()
    {
        if(Request()->isGet()){
            $this->headData();
            $this->export_csv($this->head, [], $this->name, []);
        }
    }
    /************************************** 私有 ********************************************* */
    /**
    * 导入头部
    */
    private function headData()
    {
        $this->ty = Request()->param('ty');
        if($this->ty == 'cate'){
            $this->head = ['上级ID','名字'];
            $this->name = '维修设备导入模版';
        }else if($this->ty == 'fault'){
            $this->head = ['故障描述'];
            $this->name = '维修故障导入模版';
        }else if($this->ty == 'outward'){
            $this->head = ['外观描述'];
            $this->name = '外观描述导入模版';
        }else if($this->ty == 'message'){
            $this->head = ['短信模版','短信内容'];
            $this->name = '短信导入模版';
        }else{
            $this->error(config('status.ERROR_SIX'));
        }
    }
    /**
     * 导入文件验证
     */
    private function validateFile()
    {
        $this->valiteFile();
        $this->valiteError();
        $this->valiteMinSize(config('parameter.excel_min_size'));
        $this->valiteMaxSize(config('parameter.excel_max_size'));
        $this->getEnd();
        $this->valiteEnd(config('parameter.excel_end'));
    }
    /**
     * 获取导入数据
     */
    private function getFileData()
    {
        $end = pathinfo($this->file['name'],PATHINFO_EXTENSION);
        switch($end){
            case 'xls':
            case 'xlsx':
            return $this->getExcelData();break;
            case 'csv': return $this->getCsvData();;break;
            default: $this->error($this->msg['file_end']);break;
        }
    }

    /**
    * 获取csv数据
    */
    private function getCsvData()
    {
        $data = file_get_contents($this->file['tmp_name']);
        $data = explode("\n", $data);
        $len = count($data);
        unset($data[0]);
        unset($data[$len-1]);
        if(empty($data)){
            $this->error(config('status.ERROR_TWO'));
        }
        foreach($data as $k => $v){
            $v = mb_convert_encoding($v, "UTF-8", "GBK");
            $this->excelData[] = explode(',', $v);
        }
    }
    /**
    * 获取xls|xlsx数据
    */
    private function getExcelData()
    {
        $objPHPExcel = PHPExcel_IOFactory::load($this->file['tmp_name']);//读取上传的文件
        $this->excelData = $objPHPExcel->getSheet(0)->toArray();//获取其中的数据
        unset($this->excelData[0]);
        if(empty($this->excelData)){
            $this->error(config('status.ERROR_TWO'));
        }
    }
    /**
     * 导入数据模型
     */
    private function exportModel()
    {
        $this->ty = Request()->param('ty');
        $this->type = Request()->param('type');
        switch($this->ty){
            case 'cate':
            case 'fault':
            case 'outward':
            $this->model = model('repair/Fault');break;
            case 'message': $this->model = model('message/Message');break;
            default: $this->error(config('status.ERROR_SIX'));break;
        }
        // if($ty == 'fault_cate'){
        //     $this->model = model('repair/Fault');
        //     $this->field = ['']
        // }
    }
    
}